// pages/center/center.js
const wxapi = require("../../utils/wxapi");
import { Util } from "../../utils/util";
import { API_ASIAPD_URL, API_SNZO_FILE_URL, API_SNZO_URL } from "../../utils/wxapi";
const CryptoJS = require('../../utils/crypto-js');
import drawQrcode from '../../utils/weapp.qrcode.esm.js'
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    userSpace: null,
    isUnitUser: false,
    listOfData: [],
    worksTypeOfData: null,
    currentSelected: 3,
    snzoImgUrl: API_SNZO_FILE_URL,
    pageParams: { pageNum: 1, pageSize: 10 },
    total: 0,
    scrollTopPx: 0,
    canScroll: false,
    showEntrust: false,
    entrustInfo: null,
    isHandle: false,
    isTriggered: false,
    showQrcode: false,
    qrcodeUrl: null
  },

  /**
   * 获取艺术品类型
   */
  getWorksType() {
    wxapi.getStNumWorksType({ standby3: 1 }).then(res => {
      if (res.status === 200) {
        const result = res.data.filter(item => {
          item.typeName = item.typeName.slice(0, 2);
          return item;
        });
        this.setData({
          worksTypeOfData: result
        })
      }
    })
  },

  /**
   * 获取艺术品列表
   */
  getWorksList() {
    wx.showLoading({
      title: '加载中...',
    })
    const bodyParams = {
      softDelete: 1,
      standby1: app.globalData.userInfo.cardNo
    };
    const body = Util.trimNulls(bodyParams);
    const params = Util.trimNulls(this.data.pageParams);
    let pageParams = '';
    for (const key in params) {
      if (Object.hasOwnProperty.call(params, key)) {
        const value = params[key];
        pageParams += `&${key}=${value}`
      }
    }
    wxapi.selectWorksByExample(body, pageParams).then(res => {
      wx.hideLoading();
      this.setData({
        isTriggered: false
      })
      if (res.status === 200) {
        if (this.data.pageParams.pageNum === 1) {
          this.data.listOfData = [];
          this.setData({
            scrollTopPx: 0
          })
        }
        const listOfData = res.data.data;
        listOfData.map((item) => {
          item.isReportLoading = false;
          item.isAuthLoading = false;
          item.isEntrustLoading = false;
          return item;
        });
        const newData = this.data.listOfData.concat(listOfData);
        this.setData({
          listOfData: newData,
          total: res.data.total,
          canScroll: true
        })
      }
    })
  },

  /**
   * 获取用户空间信息
   */
  getSpaceMsg() {
    wxapi.selectSpaceMsg({ stk: app.globalData.userInfo.cardNo }).then(res => {
      if (res.status === 200) {
        this.setData({
          userSpace: res.data
        })
      }
    })
  },

  /**
   * 预览艺术品
   * @param {*} e 
   */
  previewImage(e) {
    const worksItem = e.currentTarget.dataset.worksItem;
    if (worksItem.tabStnumWorkses[0].standby2.indexOf('image') !== -1 || worksItem.tabStnumWorkses[0].standby2.indexOf('video') !== -1) {
      wx.previewMedia({
        sources: [
          {
            url: this.data.snzoImgUrl + worksItem.tabStnumWorkses[0].standby1,
            type: worksItem.tabStnumWorkses[0].standby2.split('/')[0]
          }
        ],
      })
    }
  },

  /**
   * 校验用户类别
   * status 200 集团用户 status 400 个人用户
   */
  checkUserType() {
    wxapi.selectUnitUserByStk({ stk: app.globalData.userInfo.cardNo }).then(res => {
      if (res.status === 200) {
        this.setData({
          isUnitUser: true
        })
      } else if (res.status === 400) {
        this.setData({
          isUnitUser: false
        })
        this.getSpaceMsg();
      }
    })
  },

  /**
   * 获取用户基本信息
   */
  getUserInfo() {
    const allParams = {
      cardNo: app.globalData.userInfo.cardNo,
      timestamp: new Date().getTime()
    };
    const trimParams = Util.trimNulls(allParams);
    const pendSign = { ...trimParams, url: '/card/detail' };
    const sign = Util.jsonSort(pendSign);
    const md5Sign = CryptoJS.MD5(sign);
    const params = { sign: md5Sign, ...trimParams };
    const headers = {
      'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
    };
    wxapi.queryCardInfo(params, headers).then(res => {
      if (res.code === 20000) {
        const userInfo = Object.assign(app.globalData.userInfo, { balance: res.data.balance, availableBalance: res.data.availableBalance, prize: res.data.prize })
        this.setData({
          userInfo
        })
        app.globalData.userInfo = userInfo;
        wx.setStorageSync('userInfo', JSON.stringify(userInfo));
      } else if (res.code === 20005) {
        wx.showModal({
          title: '提示信息',
          content: res.message,
          confirmText: '登录',
          complete: (res) => {
            app.globalData.userInfo = null;
            app.globalData.token = null;
            wx.removeStorage({
              key: 'userInfo',
            })
            wx.removeStorage({
              key: 'token',
            })
            if (res.cancel) {
              wx.switchTab({
                url: '/pages/index/index',
              })
            }
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/login/login',
              })
            }
          }
        })
      }
    })
  },

  /**
   * 滑到最底部加载 获取分页数据
   */
  scrollToLower(e) {
    if (this.data.listOfData.length === this.data.total) {
      return;
    }
    this.setData({
      canScroll: false
    })
    this.data.pageParams.pageNum++
    this.getWorksList();
  },

  /**
   * 下拉刷新
   */
  refresherToLoad() {
    this.data.pageParams.pageNum = 1;
    this.getWorksList();
    this.getUserInfo();
  },

  /**
   * 申请认证
   * @param {*} e 
   */
  applyAuth(e) {
    if (this.data.isHandle) {
      return;
    }
    this.data.isHandle = true;
    const worksIndex = e.currentTarget.dataset.worksIndex;
    const worksItem = this.data.listOfData[worksIndex];
    worksItem.isAuthLoading = true;
    this.setData({
      listOfData: this.data.listOfData
    })
    const worksIds = [worksItem.tabStnumWorksMsg.id];
    wxapi.askAuth(worksIds, { stk: app.globalData.userInfo.cardNo }).then(res => {
      this.data.isHandle = false;
      if (res.status === 200) {
        wx.navigateTo({
          url: '/pages/center/auth/payMode/payMode',
          success: (res) => {
            res.eventChannel.emit('worksMsg', { worksItem, worksTypeOfData: this.data.worksTypeOfData });
          }
        })
      } else {
        wx.showModal({
          title: '提示信息',
          content: res.msg || res.message,
          showCancel: false,
          complete: (res) => {
            if (res.confirm) {
              worksItem.isAuthLoading = false;
              this.setData({
                listOfData: this.data.listOfData
              })
            }
          }
        })
      }
    })
  },

  /**
   * 上架商品
   */
  worksOnline(e) {
    if (this.data.isHandle) {
      return;
    }
    this.data.isHandle = true;
    const worksIndex = e.currentTarget.dataset.worksIndex;
    const worksItem = this.data.listOfData[worksIndex];
    wx.navigateTo({
      url: '/pages/center/exchange/exchange',
      success: (res) => {
        this.data.isHandle = false;
        res.eventChannel.emit('worksMsg', { worksItem, worksTypeOfData: this.data.worksTypeOfData });
      }
    })
  },

  /**
   * 修改价格 校验状态
   * @param {*} e 
   */
  updatePriceBeforeCheck(e) {
    if (this.data.isHandle) {
      return;
    }
    this.data.isHandle = true;
    const worksItem = e.currentTarget.dataset.worksItem;
    wxapi.updatePriceBeforeCheck(worksItem.tabStnumWorksMsg).then(res => {
      this.data.isHandle = false;
      if (res.status === 200) {
        wx.navigateTo({
          url: '/pages/center/exchange/exchange',
          success: (res) => {
            res.eventChannel.emit('worksMsg', { worksItem, worksTypeOfData: this.data.worksTypeOfData });
          }
        })
      } else {
        wx.showModal({
          title: '提示信息',
          content: res.msg || res.message,
          showCancel: false
        })
      }
    })
  },

  /**
   * 预览评价报告
   * @param {*} e 
   */
  previewReport(e) {
    const fileUrl = e.currentTarget.dataset.fileUrl;
    wx.downloadFile({
      url: wxapi.API_SNZO_FILE_URL + fileUrl,
      success: (res) => {
        const filePath = res.tempFilePath;
        wx.openDocument({
          filePath,
          showMenu: true,
          fileType: 'pdf'
        })
      }
    })
  },

  /**
   * 委托出售
   * @param {*} e 
   */
  entrustWorks(e) {
    const entrustMsg = e.currentTarget.dataset.worksItem;
    this.setData({
      showEntrust: true,
      entrustInfo: entrustMsg.tabStnumWorksMsg
    })
  },

  /**
   * 确定委托
   * @param {*} e 
   */
  confirmEntrust(e) {
    if (this.data.isHandle) {
      return;
    }
    this.data.isHandle = true;
    const entrustInfo = e.detail.entrustInfo;
    if (!entrustInfo.expectPrice) {
      wx.showModal({
        title: '提示信息',
        content: '请填写意向价格',
        showCancel: false
      })
    }
    wx.showLoading({
      title: '委托中...',
    })
    const bodyParams = Object.assign(
      { stk: app.globalData.userInfo.cardNo, entrustType: 1, item: 2 },
      entrustInfo
    )
    wxapi.entrustBeforeVerfity(bodyParams).then(res => {
      if (res.status === 200) {
        wxapi.activeEntrustSell(Util.trimNulls(bodyParams)).then(result => {
          wx.hideLoading()
          this.data.isHandle = false;
          this.cancelPopup();
          if (result.status === 200) {
            wx.showToast({
              title: '委托成功',
              success: () => {
                this.getWorksList();
              }
            })
          } else if (res.status === 400) {
            wx.showModal({
              title: '提示信息',
              content: result.msg,
              showCancel: false
            })
          }
        })
      } else {
        wx.hideLoading()
        this.data.isHandle = false;
        wx.showModal({
          title: '提示信息',
          content: res.msg,
          showCancel: false
        })
      }
    })
  },

  /**
   * 取消弹窗
   */
  cancelPopup() {
    this.setData({
      showEntrust: false,
      entrustInfo: null
    })
  },

  /**
   * 下载艺术品
   * @param {*} e 
   */
  downloadWorks(e) {
    if (this.data.isHandle) {
      return;
    }
    this.data.isHandle = true;
    wx.showLoading({
      title: '下载中...',
    })
    const worksInfo = e.currentTarget.dataset.worksItem;
    wxapi.selectRealPathById({ id: worksInfo.tabStnumWorksMsg.id }).then(res => {
      if (res.status === 200 && res.data) {
        const fileUrl = wxapi.API_SNZO_FILE_URL + res.data.works[0].photoRealPath;
        wx.downloadFile({
          url: fileUrl,
          success: (res) => {
            if (res.statusCode === 200) {
              // 保存图片到相册
              const fileType = fileUrl.split('.')[1];
              if (fileType.toLowerCase() === 'mp4') {
                wx.saveVideoToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: () => {
                    this.data.isHandle = false;
                    wx.hideLoading()
                    wx.showToast({
                      title: '下载成功',
                    })
                  },
                  fail: () => {
                    this.data.isHandle = false;
                    wx.hideLoading()
                    wx.showToast({
                      title: '下载失败',
                      icon: 'error'
                    })
                  }
                })
              } else {
                wx.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: () => {
                    this.data.isHandle = false;
                    wx.hideLoading()
                    wx.showToast({
                      title: '下载成功',
                    })
                  },
                  fail: () => {
                    this.data.isHandle = false;
                    wx.hideLoading()
                    wx.showToast({
                      title: '下载失败',
                      icon: 'error'
                    })
                  }
                })
              }

            } else {
              this.data.isHandle = false;
              wx.hideLoading()
              wx.showToast({
                title: '下载失败',
                icon: 'error'
              })
            }
          },
          fail: (res) => {
            this.data.isHandle = false;
            wx.hideLoading()
            wx.showToast({
              title: '下载失败',
              icon: 'error'
            })
          }
        })
      } else {
        this.data.isHandle = false;
        wx.hideLoading()
        wx.showToast({
          title: '下载失败',
          icon: 'error'
        })
      }
    })
  },

  /**
   * 退出登录
   */
  logout() {
    if (this.data.isHandle) {
      return;
    }
    this.data.isHandle = true;
    wxapi.logout(app.globalData.userInfo.cardNo, app.globalData.token).then(res => {
      this.data.isHandle = false;
      app.globalData.userInfo = null;
      app.globalData.token = null;
      wx.removeStorage({
        key: 'userInfo',
      })
      wx.removeStorage({
        key: 'token',
      })
      wx.switchTab({
        url: '/pages/index/index',
      })
    })
  },

  /**
   * 生成二维码
   */
  createQrcode() {
    this.setData({
      showQrcode: true
    })
    const query = wx.createSelectorQuery()
    query.select('#myQrcode')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        var canvas = res[0].node;
        var img = canvas.createImage();
        img.src = '/images/icon_avatarArt_logo.png';
        img.onload = () => {
          var options = {
            canvas: canvas,
            canvasId: 'myQrcode',
            width: 260,
            // padding: 30,
            background: '#ffffff',
            foreground: '#000000',
            text: `${API_ASIAPD_URL}/api/scanCode/${app.globalData.userInfo.cardNo}`,
            image: {
              imageResource: img,
              width: 80,
              height: 72,
              round: false
            }
          }
          drawQrcode(options).then(() => {
            wx.canvasToTempFilePath({
              canvasId: 'myQrcode',
              canvas: canvas,
              x: 0,
              y: 0,
              width: 260,
              height: 260,
              destWidth: 260,
              destHeight: 260,
              success: (res) => {
                this.data.qrcodeUrl = res.tempFilePath;
              },
              fail(res) {
                console.error(res)
              }
            })
          })
        }
      })

  },

  /**
   * 分享二维码
   */
  shareQrcode() {
    wx.showShareImageMenu({
      path: this.data.qrcodeUrl,
      entrancePath: '/pages/register/register',
      success: () => {
        wx.showToast({
          title: '成功',
        })
      }
    })
  },

  /**
   * 关闭二维码弹窗
   */
  closeQrcode() {
    this.setData({
      showQrcode: false
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3
      })
    }
    if (app.globalData.token) {
      this.data.pageParams.pageNum = 1;
      this.getWorksType();
      this.getWorksList();
      this.getUserInfo();
      this.checkUserType();
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {

  }
})